import RenderCell from 'packages/BaseTableCell/renderCell.js';
import formatColumn from 'packages/BaseTableCell/formatColumn';
import { formatDate } from 'pub-bbx-utils';
import EventStateEnum from '@model/enum/EventStateEnum.ts';
import { EventCreateMethodLabelEnum } from '@model/enum/LabelEnum.ts';
import { fmt_datetime } from '@src/filter/fmt'
import { isOpenData } from '@src/util/platform'
import { formattedOpenDataTooltip } from '@service/OpenDataService.ts'
import { 
  isNotSupportedDisplayField, 
  isSystemFiled, 
} from '@service/FieldService'
import { fmt_form_address } from '@src/filter/form'
import { isUndefined } from '@src/util/type'
import i18n from '@src/locales';
const $t = i18n.t.bind(i18n);

// 高级搜索
export const getAdvancedFields = (vm) => {
  
  let that = vm;
  const customerField = that.customerField || {}
  const customerOption = customerField?.setting?.customerOption || {}
  
  return [
    {
      fieldName: 'customer', // cusId
      displayName: $t('common.base.customer'),
      formType: 'text',
    },
    {
      fieldName: 'tlmName', // lmId
      displayName: $t('common.base.contact'),
      formType: 'select',
      show: customerOption.linkman
    },
    {
      fieldName: 'product', // productId
      displayName: $t('common.base.product'),
      formType: 'text',
      show: customerOption.product
    },
    {
      fieldName: 'createUser',
      displayName: $t('common.base.column.createPerson'),
      formType: 'user',
      setting: {
        isMulti: false, 
      },
      defineType: ''
    },
    {
      fieldName: 'executor',
      displayName: $t('common.fields.executorUser.displayName'),
      formType: 'user',
      setting: {
        isMulti: false, 
      },
      defineType: ''
    },
    {
      fieldName: 'synergyId',
      displayName: $t('common.fields.synergies.displayName'),
      formType: 'user',
      setting: {
        isMulti: false, 
      },
      defineType: ''
    },
    {
      fieldName: 'address',
      displayName: $t('common.base.locationMap.address'),
      formType: 'text',
      defineType: '',
      show: customerOption.address
    },
    {
      isSystem: 1,
      fieldName: 'createTime',
      displayName: $t('common.base.column.createTime'),
      formType: 'datetime',
      orderId: 1,
    },
    {
      fieldName: 'allotTime',
      displayName: $t('common.base.allocationTime'),
      formType: 'datetime',
      setting: {
        isTimeSplit: true, 
      },
    },
    {
      fieldName: 'startTime',
      displayName: $t('common.base.startTime'),
      formType: 'datetime',
      setting: {
        isTimeSplit: true, 
      },
    },
    {
      fieldName: 'completeTime',
      displayName: $t('common.base.completeTime'),
      formType: 'datetime',
      setting: {
        isTimeSplit: true, 
      },
    },
    {
      fieldName: 'evaluateTime',
      displayName: $t('task.detail.components.evaluateTime'),
      formType: 'datetime',
      setting: {
        isTimeSplit: true, 
      },
    },
    {
      fieldName: 'isEvaluate',
      displayName: $t('common.customer.questionnaire.evaluateState'),
      formType: 'select',
      setting: {
        isMulti: false, 
        dataSource: [
          {
            text: $t('common.base.all'),
            value: ""
          },
          {
            text: $t('common.base.notEvaluated'),
            value: '0'
          },
          {
            text: $t('common.base.evaluated'),
            value: '1'
          }
        ]
      }
    },
    {
      fieldName: 'sourceList',
      displayName: $t('common.base.createSource'),
      formType: 'select',
      setting: {
        isMultiFlag: true,
        isMulti: true,
        dataSource: [
          {
            // TODO: dataSource中的value需不需要翻译？
            text: $t('task.list.displayName.manualCreate'),
            value: '手动创建'
          },
          {
            text: $t('task.list.displayName.importCreate'),
            value: '导入创建'
          },
          {
            text: $t('event.list.text7'),
            value: '客户自助'
          },
          {
            text: $t('task.list.apiCreate'),
            value: 'API创建'
          },
          {
            text: $t('event.list.text13'),
            value: '系统创建'
          },
        ]
      }
    },
    {
      fieldName: 'degree',
      displayName: $t('common.base.degree'),
      formType: 'select',
      setting: {
        isMulti: false, 
        dataSource: [
          {
            text: $t('common.base.all'),
            value: ""
          },
          {
            text: $t('common.base.satisfactionDegree.1'),
            value: "满意"
          },
          {
            text: $t('common.base.satisfactionDegree.2'),
            value: "一般"
          },
          {
            text: $t('common.base.satisfactionDegree.3'),
            value: "不满意"
          }
        ]
      }
    },
    {
      fieldName: 'onceRollback',
      displayName: $t('common.task.exceptionStatus.onceRollback'),
      formType: 'select',
      setting: {
        isMulti: false,
        dataSource: [
          {
            text: $t('common.base.all'),
            value: ""
          },
          {
            text: $t('common.base.yes'),
            value: '1'
          },
          {
            text: $t('common.base.no'),
            value: '0'
          }
        ]
      }
    },
    {
      fieldName: 'inApprove',
      displayName: $t('task.list.displayName.approveStatus'),
      formType: 'select',
      setting: {
        isMulti: false, 
        dataSource: [
          {
            text: $t('common.base.all'),
            value: ""
          },
          {
            text: $t('common.base.usualStatus.approving'),
            value: '1'
          },
          {
            text: $t('common.event.approveStatus.noApprove'),
            value: '0'
          }
        ]
      }
    },
    {
      fieldName: 'taskNo',
      displayName: $t('common.fields.relationTask.displayName'),
      formType: 'text',
    },
    {
      fieldName: 'planStartTime',
      displayName: $t('common.form.type.planStartTime'),
      formType: 'datetime',
      setting: {
        isTimeSplit: true, 
      },
    },
    {
      fieldName: 'planEndTime',
      displayName: $t('common.form.type.planEndTime'),
      formType: 'datetime',
      setting: {
        isTimeSplit: true, 
      }
    },
  ].map(item => {
    return {
      ...item,
      setting: item.setting || {},
      defaultValue: null,
      show: item.show ?? true,
      visable: item.visible ?? true,
      isSearch: item.isSearch ?? 1,
      isNull: item.isNull ?? 1,
      isSystem: item.isSystem ?? 1,
      orderId: item.orderId ?? 1,
    }
  });
}


// 列表 && 选择列
export const getColumnFields = (vm) => {
  
  const that = vm;
  const customerField = that.customerField || {}
  const customerOption = customerField?.setting?.customerOption || {}

  const fields = [
    {
      fieldName: 'eventNo',
      displayName: $t('common.form.type.eventNo'),
      sortable: 'custom',
      sortName: 'eventNo',
      isSystem: 1,
      dataType: 'string',
      width: 230,
      renderCell: (h, col, row) => {
        return RenderCell.renderEvent.call(that, h, row, that.allowEventViewDetail);
      }
    },
    {
      displayName: $t('customer.detail.customerEventTable.table.label.templateId'),
      fieldName: 'eventType',
      sortable: 'custom',
      sortName: 'templateId',
      isSystem: 1,
      dataType: 'string',
      renderCell: (h, col, row) => {
        return (<div>{row.templateName || ''}</div>)
      }
    },
    {
      fieldName: 'eventCustomer',
      displayName: $t('common.base.customer'),
      sortable: 'custom',
      sortName: 'cusName',
      isSystem: 1,
      dataType: 'string',
      renderCell: (h, col, row) => {
        
        if (!row.cusName) {
          return null
        }
        
        const isLink = row.cusName.match(/>([^<>]*)</) 
        const displayName = isLink ? row.cusName.match(/>([^<>]*)</)[1] : row.cusName
        
        return RenderCell.renderCustomer.call(that, h, displayName, row.cusId, isLink)
      }
    },
    {
      fieldName: 'eventCustomerLinkman',
      displayName: $t('common.base.contact'),
      show: customerOption.linkman,
      visibleForSelectColumn: customerOption.linkman,
      renderCell: (h, col, row) => {
        return <div>{ row.lmName }</div>
      }
    },
    {
      fieldName: 'eventCustomerLinkmanPhone',
      displayName: $t('common.base.phone'),
      show: customerOption.linkman,
      visibleForSelectColumn: customerOption.linkman,
      renderCell: (h, col, row) => {
        return <div>{ row.lmPhone }</div>
      }
    },
    {
      fieldName: 'eventCustomerAddress',
      displayName: $t('common.base.locationMap.customerAddress'),
      show: customerOption.address,
      visibleForSelectColumn: customerOption.address,
      width: 210,
      renderCell: (h, col, row) => {
        
        if(Object.keys(row.cusAddress).length === 0) {
          return <div></div>
        }
        return <div> {fmt_form_address(row?.cusAddress || {})}</div>
      }
    },
    {
      fieldName: 'eventCustomerProducts',
      displayName: $t('common.base.product'),
      show: customerOption.product,
      visibleForSelectColumn: customerOption.product,
      renderCell: (h, col, row) => {
        return (<div>
          {row.products
            && row.products.map((product) => product.name).join(', ')
          }
        </div>);
      }
    },
    {
      fieldName: 'eventState',
      displayName: $t('common.base.status'),
      renderCell: (h, col, row) => {
        row.state = row.isPaused ? 'paused' : row.state
        let displayName = row.state && EventStateEnum.getName(row.state);
        return RenderCell.renderEventState(h, displayName, row.state);
      }
    },
    {
      fieldName: 'eventCreateUser',
      displayName: $t('common.base.column.createPerson'),
      sortable: 'custom',
      sortName: 'createUserName',
      isSystem: 1,
      dataType: 'string',
      renderCell: (h, col, row) => {
        if(row.source === 'API创建') {
          return <div>{ row.createUserName }</div>
        } else if(row.source === '客户自助') {
          return <div>{ row.source }</div>
        } else if(row.source === '手动创建' || row.source === '导入创建' || row.source === '系统创建') {
          return RenderCell.renderUser.call(that, h, row.createUserName, row.createUserId, that.initData.canSeeUser, row.createUserStaffId);
        }
      }
    },
    {
      fieldName: 'eventCreateTime',
      displayName: $t('common.base.column.createTime'),
      sortable: 'custom',
      sortName: 'createTime',
      isSystem: 1,
      dataType: 'date',
      renderCell: (h, col, row) => {
        return <div>{formatDate(row.createTime)}</div>;
      }
    },
    {
      fieldName: 'eventAllotTime',
      displayName: $t('common.base.allocationTime'),
      sortable: 'custom',
      sortName: 'allotTime',
      isSystem: 1,
      dataType: 'date',
      renderCell: (h, col, row) => {
        return <div>{formatDate(row.allotTime)}</div>;
      }
    },
    {
      fieldName: 'eventStartTime',
      displayName: $t('common.base.startTime'),
      sortable: 'custom',
      sortName: 'startTime',
      isSystem: 1,
      dataType: 'date',
      renderCell: (h, col, row) => {
        return <div>{formatDate(row.startTime, 'YYYY-MM-DD HH:mm')}</div>;
      }
    },
    {
      fieldName: 'eventExecutor',
      displayName: $t('common.fields.executorUser.displayName'),
      renderCell: (h, col, row) => {
        return RenderCell.renderUser.call(that, h, row.executorName, row.executorId, that.initData.canSeeUser, row.executorStaffId);
      }
    },
    {
      fieldName: 'eventSynergies',
      displayName: $t('common.fields.synergies.displayName'),
      renderCell: (h, col, row) => {
        if(isOpenData) {
          return (
            <div>
              {row.synergies && row.synergies.map((synergie) => <open-data type="userName" openid={synergie.staffId}></open-data>)}
            </div>
          );
        }
        return (<div>
          {row.synergies && row.synergies.map((synergie) => synergie.displayName).join(', ')}
        </div>);
      }
    },
    {
      fieldName: 'eventCompleteTime',
      displayName: $t('common.base.completeTime'),
      sortable: 'custom',
      sortName: 'completeTime',
      isSystem: 1,
      dataType: 'date',
      renderCell: (h, col, row) => {
        return <div>{formatDate(row.completeTime, 'YYYY-MM-DD HH:mm')}</div>;
      }
    },
    {
      fieldName: 'eventAcceptUsedTime',
      displayName: $t('task.detail.components.respondTime'),
      renderCell: (h, col, row) => {
        return <div>{row.acceptUsedTimeStr}</div>;
      }
    },
    {
      fieldName: 'eventWorkUsedTime',
      displayName: $t('task.detail.components.workTime'),
      renderCell: (h, col, row) => {
        return <div>{row.workUsedTimeStr}</div>;
      }
    },
    {
      fieldName: 'eventFinishUsedTime',
      displayName: $t('event.list.text8'),
      renderCell: (h, col, row) => {
        return <div>{row.finishUsedTimeStr}</div>;
      }
    },
    {
      fieldName: 'eventEvaluateTime',
      displayName: $t('task.detail.components.evaluateTime'),
      sortable: 'custom',
      sortName: 'evaluateTime',
      isSystem: 1,
      dataType: 'date',
      renderCell: (h, col, row) => {
        return <div>{formatDate(row.evaluateTime, 'YYYY-MM-DD HH:mm')}</div>;
      }
    },
    {
      fieldName: 'eventEvaluateState',
      displayName: $t('common.customer.questionnaire.evaluateState'),
      renderCell: (h, col, row) => {
        return <div>{row.isEvaluate ? $t('common.base.evaluated') : $t('common.base.notEvaluated')}</div>;
      }
    },
    {
      fieldName: 'eventOnceRollback',
      displayName: $t('common.task.exceptionStatus.onceRollback'),
      renderCell: (h, col, row) => {
        return <div>{row.onceRollback ? $t('common.base.yes') : $t('common.base.no')}</div>;
      }
    },
    {
      fieldName: 'eventDegree',
      displayName: $t('common.base.degree'),
      sortable: 'custom',
      sortName: 'degree',
      isSystem: 1,
      dataType: 'string',
      renderCell: (h, col, row) => {
        return <div>{row.degree}</div>;
      }
    },
    {
      fieldName: 'eventInApprove',
      displayName: $t('task.list.displayName.approveStatus'),
      renderCell: (h, col, row) => {
        return <div>{row.inApprove ? $t('common.base.usualStatus.approving') : $t('common.event.approveStatus.noApprove')}</div>;
      }
    },
    {
      fieldName: 'eventSuggestion',
      displayName: $t('customer.detail.customerTaskTable.table.label.suggestion'),
      renderCell: (h, col, row) => {
        return <div>{row.suggestion}</div>;
      }
    },
    {
      fieldName: 'eventUpdateTime',
      displayName: $t('common.base.lastUpdate'),
      sortable: 'custom',
      sortName: 'updateTime',
      isSystem: 1,
      dataType: 'date',
      renderCell: (h, col, row) => {
        const IsHaveUpdateRecord = Boolean(row.lastUpdateRecord)
        
        // 没有更新日志
        if (!IsHaveUpdateRecord || isOpenData) {
          return (
            <div onMouseover={() => that.fetchLastUpdateRecord(row) }>
              { fmt_datetime(row.updateTime) }
            </div>
          )
        }
        
        const openDataToolTipList = formattedOpenDataTooltip(row.lastUpdateRecord || '')
        const openDataToolTipListElement = openDataToolTipList.map(openDataToolTip => {
          if (openDataToolTip.text) {
            return <span>{openDataToolTip.text}</span>
          }
          if (openDataToolTip.staffId && isOpenData) {
            return <open-data type="userName" openid={openDataToolTip.staffId}></open-data>
          }
          if (openDataToolTip.userName) {
            return <span>{openDataToolTip.userName}</span>
          }
        })
        
        // 有更新日志
        return (
          <el-tooltip
            class='item'
            effect='dark'
            placement='top'
          >
            <div slot="content">
              { openDataToolTipListElement }
            </div>
            <div>
              { fmt_datetime(row.updateTime) }
            </div>
          </el-tooltip>
        )
      }
    },
    {
      fieldName: 'source',
      displayName: $t('common.base.createSource'),
      renderCell: (h, col, row) => {
        return <div>{EventCreateMethodLabelEnum[row.source] || row.source}</div>;
      }
    },
    {
      fieldName: 'isTransferToTask',
      displayName: $t('event.list.text9'),
      renderCell: (h, col, row) => {
        return <div>{row.isTransferToTask === 1 ? $t('common.base.yes') : $t('common.base.no')}</div>;
      }
    },
    {
      fieldName: 'isEventRelevance',
      displayName: $t('common.fields.relationTask.displayName'),
      renderCell: (h, col, row) => {
        return <div>
          {
            row.tasks && row.tasks.map(item => {
              const params = {
                id: item.taskId,
                taskNo: item.taskNo
              }
              return RenderCell.renderTask.call(that, h, params, true)
            })
          }
        </div>
      }
    },
    {
      fieldName: 'tagEvaluates',
      displayName: $t('common.customer.questionnaire.serviceTag'),
      visable: that.initData?.evaluateConfig?.useTagEvaluate,
      renderCell: (h, col, row) => {
        return <div>{row?.evaluate?.tagEvaluates ?  row.evaluate.tagEvaluates : ''}</div>;
      }
    },
    {
      fieldName: 'eventPlanStartTime',
      displayName: $t('common.form.type.planStartTime'),
      sortable: 'custom',
      sortName: 'planStartTime',
      dataType: 'date',
      renderCell: (h, col, row) => {
        const dateType = col?.setting?.dateType || 'YYYY-MM-DD HH:mm'
        return <div>{formatDate(row.planStartTime, dateType)}</div>;
      }
    },
    {
      fieldName: 'eventPlanEndTime',
      displayName: $t('common.form.type.planEndTime'),
      sortable: 'custom',
      sortName: 'planEndTime',
      dataType: 'date',
      renderCell: (h, col, row) => {
        const dateType = col?.setting?.dateType || 'YYYY-MM-DD HH:mm'
        return <div>{formatDate(row.planEndTime, dateType)}</div>;
      }
    },
  ]

  return fields.map(item => {
    // 初始化属性
    let field = {
      ...item,
      formType: item.formType ?? 'text',
      setting: item.setting || {},
      isSystem: item.isSystem ?? 1,
      isNull: item.isNull ?? 1,
      isSearch: item.isSearch ?? 1,
      orderId: item.orderId ?? 1,
      show: item.show ?? true,
      tableName: 'event',
      minWidth: 150,
      visable: item.visable ?? true
    };
    return formatColumn(field); 
  })
};


export const getFilterConfig = (vm) => {
  const that = vm;
  return [
    {
      label: $t('event.eventState'),
      name: 'state',
      content: [
        {
          label: $t('event.list.text10'),
          value: 'all',
          count: '',
          active: true,
        },
        {
          label: $t('common.event.stateProcess.created'),
          value: 'created',
          count: '',
          active: false,
        },
        {
          label: $t('common.event.stateProcess.allocated'),
          value: 'allocated',
          count: '',
          active: false,
        },
        {
          label: $t('common.event.stateProcess.processing'),
          value: 'processing',
          count: '',
          active: false,
        },
        {
          label: $t('common.base.usualStatus.finish'),
          value: 'allFinished', // convert2Task, finished
          count: '',
          active: false,
        },
        {
          label: $t('common.event.stateProcess.offed'),
          value: 'offed',
          count: '',
          active: false,
        },
        {
          label: $t('event.list.text11'),
          value: 'exception',
          count: '',
          active: false,
        },
      ]
    },
    {
      label: $t('common.base.createAngle'),
      name: 'mySearch',
      content: [
        {
          label: $t('common.base.all'),
          value: 'all',
          active: true,
        },
        {
          label: $t('common.task.angle.create'),
          value: 'create',
          active: false,
        },
        {
          label: $t('common.task.angle.execute'),
          value: 'execute',
          active: false,
        },
        {
          label: $t('common.task.angle.synergy'),
          value: 'synergy',
          active: false,
        },
      ]
    },
    {
      label: $t('customer.detail.customerEventTable.table.label.templateId'),
      name: 'templateId', // eventType
      content: []
    },
    {
      label: $t('common.base.createTask'),
      name: 'isTransferToTask',
      content: [
        {
          label: $t('common.base.all'),
          value: 0,
          active: true,
        },
        {
          label: $t('common.base.yes'),
          value: 1,
          active: false,
        },
        {
          label: $t('common.base.no'),
          value: 2,
          active: false,
        },
      ]
    }
  ]
}

export const getExceptionFields = () => {
  return [
    {
      label: $t('event.list.text12'),
      name: 'exceptionType',
      content: [
        {
          label: $t('common.base.all'),
          value: 0,
          active: true,
        },
        {
          label: $t('common.base.usualStatus.paused'),
          value: 1,
          active: false,
        },
        {
          label: $t('common.base.usualStatus.overtime'),
          value: 2,
          active: false,
        },
      ]
    }
  ]
}

export const getExportSystemInfo = () => {
  return [
    {
      exportAlias: "state",
      displayName: $t('event.eventState'),
    },
    {
      exportAlias: "createUser",
      displayName: $t('common.base.column.createPerson'),
    },
    {
      exportAlias: "executor",
      displayName: $t('common.fields.executorUser.displayName'),
    },
    {
      exportAlias: "synergies",
      displayName: $t('common.fields.synergies.displayName'),
    },
    {
      exportAlias: "createTime",
      displayName: $t('common.base.column.createTime'),
    },
    {
      exportAlias: "allotTime",
      displayName: $t('common.base.allocationTime'),
    },
    {
      exportAlias: "startTime",
      displayName: $t('common.base.startTime'),
    },
    {
      exportAlias: "completeTime",
      displayName: $t('common.base.completeTime'),
    },
    {
      exportAlias: "acceptUsedTime",
      displayName: $t('task.detail.components.respondTime'),
    },
    {
      exportAlias: "workUsedTime",
      displayName: $t('task.detail.components.workTime'),
    },
    {
      exportAlias: "finishUsedTime",
      displayName: $t('event.list.text8'),
    },
    {
      exportAlias: "evaluateTime",
      displayName: $t('task.detail.components.evaluateTime'),
    },
    {
      exportAlias: "evaluateState",
      displayName: $t('common.customer.questionnaire.evaluateState'),
    },
    {
      exportAlias: "onceRollback",
      displayName: $t('common.task.exceptionStatus.onceRollback'),
    },
    {
      exportAlias: "degree",
      displayName: $t('common.base.degree'),
    },
    {
      exportAlias: "suggestion",
      displayName: $t('customer.detail.customerTaskTable.table.label.suggestion'),
    },
    {
      exportAlias: "source",
      displayName: $t('common.base.createSource'),
    },
    {
      exportAlias: "isTransferToTask",
      displayName: $t('event.list.text9'),
    },
    {
      exportAlias: "inApprove",
      displayName: $t('task.list.displayName.approveStatus'),
    },
    {
      exportAlias: "taskNo",
      displayName: $t('common.fields.relationTask.displayName'),
    }
  ]
}